package com.jiuyou.storeController.member;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.core.domain.model.LoginMember;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.img.ImgUtil;
import com.ruoyi.common.utils.tencentCos.CosAppendObject;
import com.ruoyi.common.utils.tencentCos.CosConstants;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.service.MemberTokenService;
import com.ruoyi.member.service.IMemberService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.wechat.AES;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chengliang
 * @date 2021/5/20
 **/
@RestController
//@RequestMapping("/aa/member")
public class MemberRegisterStoreController extends BaseController {
    @Autowired
    private IMemberService memberService;

    @Autowired
    private MemberTokenService tokenService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ISysConfigService configService;
    /**
     * 进来获取此人的OpenId回传
     */
    @RequestMapping("/getOpenId")
    public Map getOpenId(String code) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("exist",false);

        //手机号注册方式
        String content = memberService.converWechatOpenId(code);
        JSONObject jsonObject = JSON.parseObject(content);
        if (jsonObject.get("session_key") == null || jsonObject.get("openid") == null) {
            throw new Exception();
        }
        String openId = jsonObject.getString("openid");
        Member exist = memberService.selectMemberByOpenId(openId);
        String unionid=jsonObject.getString("unionid");
        if(null != exist){
            String token = tokenService.createToken(new LoginMember(exist));
            map.put("success",true);
            map.put("member",exist);
            map.put("exist",true);
            map.put("token",token);
            map.put("openId",openId);
            return map;
        }

        Member member = new Member();
        member.setOpenId(openId);
        member.setNickName("陌生用户");

        memberService.insertMember(member);
        Member regist = memberService.selectMemberById(member.getId());
        String token = tokenService.createToken(new LoginMember(regist));
        map.put("member",regist);
        map.put("token",token);
        map.put("success",true);
        map.put("openId",openId);
        return map;
    }
    /**
     * 进来获取此人的OpenId回传
     */
    @RequestMapping("/auto-login")
    public Map autoLogin(String openId) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("exist",false);

        Member m = new Member();
        m.setOpenId(openId);
        List<Member> members = memberService.selectMemberList(m);
        map.put("success",true);
        if(members.size()>0){
            Member member = members.get(0);
            String token = tokenService.createToken(new LoginMember(member));
            map.put("member",member);
            map.put("token",token);
            map.put("exist",true);
        }
        return map;
    }
    /**
     * 检测当前用户token是否过期
     */
   /* @RequestMapping("/check-login")
    public Map<String,Object> checkLogin(String openId ,String code) {
        Map map = new LinkedHashMap(3);
        map.put("online",false);
        map.put("regist",false);
        LoginMember loginUser = tokenService.getLoginMember();

        if(loginUser != null){
            tokenService.verifyToken(loginUser);
            map.put("online",true);
            map.put("regist",true);
            return map;
        }

        Member member = memberService.selectMemberByOpenId(openId);
        if(member != null){
            map.put("online",false);
            map.put("regist",true);
            map.put("memeber",member);
        }


        return map;

    }*/

    /**
     * 进来获取此人的OpenId回传
     */
    @RequestMapping("/register")
    public Map register(String encryptedData,String iv, String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("exist",false);


        String content = memberService.converWechatOpenId(code);
        JSONObject jsonObject = JSON.parseObject(content);
        if (jsonObject.get("session_key") == null || jsonObject.get("openid") == null) {
            throw new CustomException("注册失败");
        }
        String session_key = jsonObject.get("session_key").toString();
        String phoneStr = AES.wxDecrypt(encryptedData, session_key, iv);
        cn.hutool.json.JSONObject phoneJson = JSONUtil.parseObj(phoneStr);
        //没有区号的手机号
        if(phoneJson.get("purePhoneNumber") == null){
            throw new CustomException("注册失败");
        }
        map.put("phone",phoneJson.get("purePhoneNumber").toString());
        Member m = new Member();
        m.setOpenId(jsonObject.getString("openid"));

        //先根据openId看看有没有此人
//        List<Member> exist = memberService.selectMemberList(m);
        Member exist = memberService.selectMemberByOpenIdOrPhone(jsonObject.getString("openid"),phoneJson.getStr("purePhoneNumber"));
        if(exist!=null){
            map.put("exist",true);
            exist.setOpenId(jsonObject.getString("openid"));
            memberService.updateMember(exist);
            String token = tokenService.createToken(new LoginMember(exist));
            map.put("member",exist);
            map.put("token",token);
            return map;
        }
        m.setPhone(phoneJson.get("purePhoneNumber").toString());

        memberService.insertMember(m);
        List<Member> members = memberService.selectMemberList(m);
        if(members.size()>0){
            Member member = members.get(0);
            String token = tokenService.createToken(new LoginMember(member));
            map.put("member",member);
            map.put("token",token);
            map.put("success",true);
        }
        return map;
    }

    //刷新用户手机号
    @RequestMapping("/flushPhone")
    public Map flushPhone(String encryptedData,String iv, String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("exist",false);
        String content = memberService.converWechatOpenId(code);
        JSONObject jsonObject = JSON.parseObject(content);
        if (jsonObject.get("session_key") == null || jsonObject.get("openid") == null) {
            throw new CustomException("注册失败");
        }
        String session_key = jsonObject.get("session_key").toString();
        String phoneStr = AES.wxDecrypt(encryptedData, session_key, iv);
        cn.hutool.json.JSONObject phoneJson = JSONUtil.parseObj(phoneStr);
        //没有区号的手机号
        if(phoneJson.get("purePhoneNumber") == null){
            throw new CustomException("注册失败");
        }
        map.put("phone",phoneJson.get("purePhoneNumber").toString());
        //默认此人一定存在
        //根据openID查找
        Member member = memberService.selectMemberByOpenId(jsonObject.getString("openid"));
        if(null == member){
            throw new ServiceException("用户不存在");
        }
        member.setPhone(phoneJson.get("purePhoneNumber").toString());
        map.put("exist",true);
        memberService.updateMember(member);
        String token = tokenService.createToken(new LoginMember(member));
        map.put("member",member);
        map.put("token",token);
        map.put("success",true);
        return map;
    }


    /**
     * 修改用户基本信息
     */
    @PostMapping("/update/basic/info")
    public AjaxResult updateBasicInfo(@RequestBody Map<String, Object> paramMap) {
        String headImgUrl = String.valueOf(paramMap.get("headImgUrl"));  //用户头像
        String nickName = StringUtils.toStringIfNull(paramMap.get("nickName"));  //昵称
//        Integer gender = Integer.valueOf(String.valueOf(paramMap.get("gender")));  //性别
        Long loginMemberId = tokenService.getLoginMemberId();

        String fileName = DateUtils.dateTime() +"-"+IdUtils.fastUUID()+"-"+DigestUtils.md5Hex(String.valueOf(loginMemberId)) + ".jpg"; //文件名
        // 上传文件路径
        String uploadDir = RuoYiConfig.getUploadPath();
        String filePath="/headImg";
        String fileAbsolutePath = uploadDir + filePath +"/"+ fileName;
        try {

            // 读取头像图片
            BufferedImage bufferedImage = ImgUtil.loadImageUrl(headImgUrl, false);
            // 输出
            File file = new File(fileAbsolutePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            ImageIO.write(bufferedImage, "jpg", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String headImg = serverConfig.getUrl() + Constants.RESOURCE_PREFIX + "/upload/headImg/" + fileName;
        if(DicConstants.SYS_Y.getCode().equals(configService.selectConfigByKey("cententOSS"))){
            Map<String, String> map = new HashMap<>(4);
            map.put("secretKey",configService.selectConfigByKey("secretKey"));
            map.put("secretId",configService.selectConfigByKey("secretId"));
            map.put("area",configService.selectConfigByKey("area"));
            map.put("bucketName",configService.selectConfigByKey("bucketName"));
            //开启腾讯oss
            headImg= CosAppendObject.AppendObjectFromLocal(map,fileName,fileAbsolutePath,"upload/"+filePath);
        }
        Member member = new Member();
        member.setId(loginMemberId);
        member.setHeadImg(headImg);
        member.setNickName(nickName);
        memberService.updateMember(member);
        LoginMember loginMember = tokenService.getLoginMember();
        loginMember.setMember(member);
        tokenService.setloginMember(loginMember);


        return AjaxResult.success(member);
    }


   /* @RequestMapping("/reload")
    public Member reload(){
        try {
            LoginMember loginMember = tokenService.getLoginMember();
            if(loginMember == null){
                return null;
            }
            return memberService.selectMemberById(loginMember.getMember().getId());
        }catch (Exception e){
            return null;
        }

    }
    @RequestMapping("/loginout")
    public void loginout(){
        Long id = tokenService.getLoginMemberId();
        memberService.loginOut(id);
        tokenService.loginOut();
    }
*/
    @RequestMapping("/remove-token")
    public void removeToken(HttpServletRequest request){
        tokenService.delloginMember(request);
    }

    /**
     * 获取最新用户信息
     * @return
     */
    @PostMapping("/getMember")
    public AjaxResult getMember() {
        Long loginMemberId = tokenService.getLoginMemberId();
        if(null==loginMemberId){
            return AjaxResult.error("获取失败01");
        }
        Member memberData=memberService.selectMemberById(loginMemberId);
        return AjaxResult.success(memberData);
    }
}

